<?php
namespace Plu\Library\Services\Platform\Media;

use Plu\Library\Services\ServiceBase,
    Httpful\Request as Request,
    Plu\Library\Models\Platform\Media\QCloudNewFileUpload as QCloudNewFileUpload,
    Plu\Library\Models\Platform\Media\QCloudTranscode as QCloudTranscode,
    Plu\Library\Services\Redis\Room\RoomRedis as RoomRedis,
    Plu\Library\Models\Platform\Media\NewMedia as NewMedia,
    Plu\Library\Models\Platform\Media\ReplayMedia as ReplayMedia;

class NewMediaService extends ServiceBase {

    const VIDEO_CACHE_TIME = 60;

    // 转码状态
    const TransType = [
        'default' => 0,
        'transcode' => 1, 
        'success' => 2
    ];

    private $transCodeRequestUrl = 'http://liveapi.longzhu.com/LiveReplay/QCloudVodProcessFile?fileid=%s&appId=%s';

    private $transCodeSadd = 'sadd:transCode:videoId';

    private $alltransCodeSadd = 'sadd:alltransCode:videoId';

    // 获取所有回访视频
    public function getVideos($start_index, $max_results, $uploadtime_start, $uploadtime_end, $title, $userId = false) {
            
        if ($userId) { 
            $redis = new RoomRedis;
            $roomId = $redis->getRoomIdByUid($userId);
            if (!$roomId) {
                return [0, 0];
            }
        }
        $model = new NewMedia;
        list($count,$items) = $model->getVideoByFilter($start_index, $max_results, $uploadtime_start, $uploadtime_end, $title, $roomId);
        $ret = $this->oldVideoFormat($items);


        return [$count, $ret];
    }

    // 获取审核回访视频
    public function getNewVideos($start, $max_results, $filter, $uploadtime_start, $uploadtime_end, $title, $userId) {

        $model = new ReplayMedia;
        list($count, $items) = $model->getVideos($start, $max_results, $filter, $uploadtime_start, $uploadtime_end, $title, $userId);
        $res = $this->dataFormat($items);    

        return [$count, $res];

    }

    private function getNickNames(array $uids) {
        $service = $this->grpc->service("go.micro.srv.user");

        $replay = $service->InfoListByUserIDs(array_map(intval, $uids));

        $data = json_decode($replay->serializeToJsonString(), true);

        return $data["data"];
    }


    private function dataFormat($items) {

        $redis = $this->getRedis('vector');

        $format = [];

        foreach ($items as $item) {

            if ($redis->sIsMember($this->transCodeSadd, $item['Id'])) {
                $transType = self::TransType['transcode'];
            } else {
                $transType = self::TransType['default'];
            }

            $Qcloud = QCloudNewFileUpload::getNewItem($item['LiveId']);


            if ($Qcloud) {
                $QcloudTranscode = QCloudTranscode::getTranscodeItem($Qcloud->FileId, false);

                if ($QcloudTranscode) {
                    $mp4Url = $QcloudTranscode->Url;
                    $redis->sRem($this->transCodeSadd, $item['Id']);
                    $transType = self::TransType['success'];
                } else {
                    $mp4Url = NULL;
                }

            }

            $time  = NewMedia::getTime($item['LiveId']); 
   
            $r = [
                'Id'     => $item['Id'],
                'videoId' => $item['VideoId'],
                'RoomId' => $item['RoomId'],
                'Title'  => $item['Title'],
                'uid'    => $item['UserId'],
                'ReportedTimes' => $item['ReportedTimes'],
                'ReplayVideoStatus' => $item['ReplayVideoStatus'],
                'ReportReasons'   => $item['ReportReasons'],
                'Cover'  => $Qcloud->Cover,
                'FileUrl'=> $Qcloud->FileUrl,
                'CreateTime' => $time->CreateTime,
                'TimeSpan'  => $Qcloud->Duration,
                'FileId'  => $Qcloud->FileId,
                'mp4Url' => $mp4Url,
                'transType' => (int)$transType,
                'DownLoad'  => $this->getFfmpegCode($Qcloud->FileUrl, $item['RoomId'], $Qcloud->CreateTime)
            ];;

            $format[] = $r;
        }

        if (!empty($format)) {
            $uids = array_column($format,  'uid');
            $userInfo = $this->getNickNames($uids);
            if (!is_array($userInfo)) {
                $userInfo = array($userInfo);
            }
            foreach($userInfo as $key => $value) {
                $format[$key]['nickname'] = $value['nickname'];
            }
        }

        return $format;
    }


    public function oldVideoFormat($items) {

        $redis = $this->getRedis('vector');

        $format = [];

        array_walk($items, function ($item, $key) use(&$format, $redis) {
            //print_r($item);
            $Qclouds = QCloudNewFileUpload::getItem($item['PlayId']);

            if ($redis->sIsMember($this->alltransCodeSadd, $item['Id'])) {
                $transType = self::TransType['transcode'];
            } else {
                $transType = self::TransType['default'];
            }

            if ($Qclouds) {

                $QcloudTranscode = QCloudTranscode::getTranscodeItem($Qclouds[0]['FileId'], false);

                if ($QcloudTranscode) {
                    $mp4Url = $QcloudTranscode->Url;
                    $redis->sRem($this->alltransCodeSadd, $item['Id']);
                    $transType = self::TransType['success'];
                } else {
                    $mp4Url = NULL;
                }

                $r = [
                    'Qclouds' => $Qclouds[0]['FileId'],
                    'Id'     => $item['Id'],
                    'RoomId' => $item['RoomId'],
                    'Title'  => $item['Title'],
                    'uid'    => $this->userIdFormat($item['RoomId']),
                    'CreateTime' => $item['CreateTime'],
                    'playId' => $item['PlayId'],
                    'mp4Url' => $mp4Url,
                    'transType' => (int)$transType,
                    'DownLoad'  => $this->getFfmpegCode($Qcloud['FileUrl'], $item['RoomId'], $item['CreateTime'])
                ];

                foreach ($Qclouds as $Qcloud) {    
                    $r['TimeSpan'] = $Qcloud['Duration'];
                    $r['Cover'] = $Qcloud['Cover'];
                    $r['FileUrl'] = $Qcloud['FileUrl'];
                }

                $format[] = $r;
            } else {
                $r = [
                    'Id'     => $item['Id'],
                    'RoomId' => $item['RoomId'],
                    'Title'  => $item['Title'],
                    'uid'    => $this->userIdFormat($item['RoomId']),
                    'CreateTime' => $item['CreateTime'],
                    'TimeSpan' => null,
                    'Cover'    => null,
                    'FileUrl'  => null,
                    'DownLoad'  => $this->getFfmpegCode(null, $item['RoomId'], $item['CreateTime'])
                ];
                $format[] = $r;
            }

        });
   

        if (!empty($format)) {
            $uids = array_column($format,  'uid');
            $userInfo = $this->getNickNames($uids);
            if (!is_array($userInfo)) {
                $userInfo = array($userInfo);
            }
            foreach($userInfo as $key => $value) {
                $format[$key]['nickname'] = $value['nickname'];
            }
        }

        return $format;

    }

    // 激活视频腾讯云转码
    public function transcodeVideo($videoId, $isAll = false) {

        if ($isAll) {
            $e = NewMedia::getItem($videoId);
            $liveId = $e->PlayId;
        } else {
            $e = ReplayMedia::getVideo($videoId, false);
            $liveId = $e->LiveId;
        }

        $Qcloud = QCloudNewFileUpload::getNewItem($liveId);

        $appId = $Qcloud->FileUrl{7};
        $fileId = $Qcloud->FileId;

        $requestUrl = sprintf($this->transCodeRequestUrl, $fileId, $appId);

        $result = Request::get($requestUrl)->send();

        if ($result->body->code !==0 || $result->body->data->code !==0 ) {
            $this->logger->log('TencentCloud Video TransCode Failed errorCode ===>'.$result->body->data->code);
            return false;
        }

        $redis = $this->getRedis('vector');

        if ($isAll) {
            $redis->sadd($this->alltransCodeSadd, $videoId);
        } else {
            $redis->sadd($this->transCodeSadd, $videoId);
        }

        return true;
    }


    public function userIdFormat($roomId) {
        $redis = new RoomRedis;
        $userId = $redis->getUidByRoomId($roomId);

        return $userId;
    }



    public function domainformat($items) {
        $redis = new RoomRedis;
        $format = [];
        foreach ($items as $item) {
            $domain = $redis->getDomains($item['RoomId']);
            $item['domain'] = $domain[0];
            $format[] = $item;
        }
        return $format;

    }

    public function getVideosByDomain($domain, $start_index, $max_results, $filter) {
        $redis = new RoomRedis;
        $roomId = $redis->getRoomId($domain);

        list($count, $items) = NewMedia::getVideosByRoomIds($roomId, $start_index, $max_results, $filter);

        $format = $this->domainformat($items);
        return array($count,$format);

    }

    public function getVideoByFilter($start_index, $max_results, $uploadtime_start, $uploadtime_end, $filter_title, $domain, $filter) {

        if ($domain) {
            $redis = new RoomRedis;
            $roomId = $redis->getRoomId($domain);
        }
        list($count, $items) = NewMedia::getVideoByFilter($start_index, $max_results, $uploadtime_start, $uploadtime_end, $filter_title, $roomId, $filter);

        $format = $this->domainformat($items);
        return [$count, $format];

    }


    public function passVideo($id) {
        $result = ReplayMedia::passVideo($id, 1);
        return $result;
    }

    // 拒绝回访视频
    public function refuseVideo($mediaId) {
        $authId = $this->cookies->get('p1u_openid');
        $authName = $this->cookies->get('p1u_username');
        $url = "http://star.api.plu.cn/livereplay/ReportReplayVideoClosure?id=".$mediaId."&authId=".$authId."&authName=".$authName;
        $cookieValue = $this->cookies->get('p1u_id')->getValue();
        $cookie = [
            'Cookie'=>'p1u_id='.$cookieValue,
            'set-cookie'=>'p1u_id='.$cookieValue.'; domain=plu.cn; path=/; HttpOnly'
        ];
        $result = Request::get($url)->addHeaders($cookie)->send();

        if ($result->body->code == 0) {
            return true;
        }

        return false;

    }

    private function getFfmpegCode($fileUrl, $roomId, $time) {
        $ffmpeg = 'ffmpeg -i '."$fileUrl".' -acodec copy -bsf:a aac_adtstoasc -vcodec copy  (在此设置转码下载路径)  '.$roomId.'.mp4';
        return $ffmpeg;
    }

    // 修改回访视频标题
    public function UpdateTitle($Id, $title, $type = false) {

        $strlen = strlen($title) + mb_strlen($title,'UTF8');
        $str = $strlen / 2;
        if ($str <1 || $str >40 ) {
            return false;
        } 
        // 从所有回放中修改
        if ($type) {
            $item = NewMedia::getItem($Id);
            $item->Title = $title;
            $item->save();
            $ansc = ReplayMedia::UpdateTitleByLiveId($item->PlayId, $title);
            return true;
        } 
        // 同步ReplayVideo
        $res = ReplayMedia::updateTitle($Id, $title);
        if ($res) {
            $ansc = NewMedia::UpdateTitleByLiveId($res->LiveId, $title);
            if ($ansc) {
                return true;
            }
        } 
        return false;


    }


}

?>

